package cn.micro.core.context;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 当前上下文
 */
public class CurrentContext extends ConcurrentHashMap<String, Object> {

    private static final TransmittableThreadLocal<? extends CurrentContext> currentContext = new TransmittableThreadLocal<CurrentContext>() {
        @Override
        protected CurrentContext initialValue() {
            return new CurrentContext();
        }
    };

    public static CurrentContext context() {
        return currentContext.get();
    }

    @Override
    public Object put(String key, Object value) {
        if (key != null && value != null) {
            return super.put(key, value);
        } else {
            return null;
        }
    }

    @Override
    public Object putIfAbsent(String key, Object value) {
        if (key != null && value != null) {
            return super.putIfAbsent(key, value);
        } else {
            return null;
        }
    }

    public static void remove() {
        context().clear();
        currentContext.remove();
    }

    public static <T> T get(String key) {
        return get(key, null);
    }

    @SuppressWarnings("unchecked")
    public static <T> T get(String key, T defaultValue) {
        return (T) context().getOrDefault(key, defaultValue);
    }

    public static boolean existsKey(String key) {
        return context().containsKey(key);
    }

    public static void set(String key, Object value) {
        context().put(key, value);
    }

    public static void setIfAbsent(String key, Object value) {
        context().putIfAbsent(key, value);
    }

    public static void removeKey(String key){
        context().remove(key);
    }

}
